<template>
  <div class="flex flex-col min-h-screen bg-background overflow-hidden">
    <!-- 顶部工具栏 -->
    <div class="flex items-center justify-between h-12 px-4 bg-background app-draggable">
      <!-- 左侧占位 -->
      <div class="flex-1"></div>

      <!-- 中间标题 -->
      <div class="flex-1 text-center">
        <h1 class="text-sm font-medium text-foreground">Joythink AI</h1>
      </div>

      <!-- 右侧控制按钮 -->
      <div class="flex-1 flex items-center justify-end gap-2 app-draggable__disabled">
        <ThemeToggle mode="dropdown" />
        <WindowControls />
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="flex-1 flex items-center justify-center p-3 sm:p-4">
      <div class="w-full max-w-xs sm:max-w-md">
        <!-- 页面标题 -->
        <div v-if="!showCreateForm" class="text-center mb-6 sm:mb-8">
          <h2 class="text-2xl sm:text-3xl font-bold text-foreground mb-2">{{ t('login.welcome') }}</h2>
          <p class="text-text-secondary text-sm sm:text-base">{{ t('login.title') }}</p>
        </div>

        <!-- 加载状态 -->
        <LoadingState v-if="loading" :message="t('common.loading')" />

        <!-- 错误状态 -->
        <ErrorState
          v-else-if="error"
          :title="t('login.loginFailed')"
          :message="error"
          :error-type="getErrorType(error)"
          @retry="loadUsers" />

        <!-- 创建用户表单 -->
        <CreateUserForm
          v-else-if="showCreateForm"
          ref="createFormRef"
          :loading="createUserLoading"
          :error="createUserError"
          @submit="handleCreateUser"
          @cancel="showCreateForm = false"
          @clear-error="createUserError = ''" />

        <!-- 无用户状态 -->
        <EmptyState v-else-if="users.length === 0" @create-user="showCreateForm = true" />

        <!-- 用户选择区域 -->
        <UserCarousel
          v-else
          ref="carouselRef"
          :users="users"
          :login-loading="loginLoading"
          :initial-index="currentUserIndex"
          @login="handleLogin"
          @create-user="showCreateForm = true" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Result, UserInfo } from '@shared/types.d';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { createUser, getAllUsers } from '@/api/system/user';
import ThemeToggle from '@/components/ThemeToggle.vue';
import WindowControls from '@/components/WindowControls.vue';
import { t } from '@/i18n';
import { useUserStore } from '@/stores/user';

import CreateUserForm from './components/CreateUserForm.vue';
import EmptyState from './components/EmptyState.vue';
import ErrorState from './components/ErrorState.vue';
import LoadingState from './components/LoadingState.vue';
import UserCarousel from './components/UserCarousel.vue';

const router = useRouter();

// 响应式数据
const users = ref<UserInfo[]>([]);
const currentUserIndex = ref(0);
const loading = ref(false);
const loginLoading = ref(false);
const error = ref<string>('');

// 创建用户相关状态
const showCreateForm = ref(false);
const createUserLoading = ref(false);
const createUserError = ref('');

// 组件引用
const carouselRef = ref<InstanceType<typeof UserCarousel>>();
const createFormRef = ref<InstanceType<typeof CreateUserForm>>();

// 加载用户列表
const loadUsers = async () => {
  loading.value = true;
  error.value = '';

  try {
    const result: Result<UserInfo[]> = await getAllUsers();
    if (result.success && result.data) {
      users.value = result.data;
      currentUserIndex.value = 0;
    } else {
      error.value = result.error || t('login.loginFailed');
    }
  } catch (err: any) {
    error.value = err.message || t('error.network.description');
  } finally {
    loading.value = false;
  }
};

// 处理用户登录
const handleLogin = async (user: UserInfo) => {
  loginLoading.value = true;

  try {
    const result = await useUserStore().login(user.id);
    if (result) {
      router.push('/home');
    }
  } catch (err: any) {
    error.value = err.message || t('login.loginFailed');
  } finally {
    loginLoading.value = false;
  }
};

// 处理创建新用户
const handleCreateUser = async (username: string) => {
  createUserLoading.value = true;
  createUserError.value = '';

  try {
    const result = await createUser(username);
    if (result.success && result.data) {
      // 创建成功，重新加载用户列表
      await loadUsers();

      // 关闭创建表单并重置
      showCreateForm.value = false;
      createFormRef.value?.reset();
      createUserError.value = '';

      // 将新用户设为当前选中用户
      const newUserIndex = users.value.findIndex((user) => user.id === result.data);
      if (newUserIndex !== -1) {
        currentUserIndex.value = newUserIndex;
      }
    } else {
      createUserError.value = result.error || t('login.loginFailed');
    }
  } catch (err: any) {
    createUserError.value = err.message || t('login.loginFailed');
  } finally {
    createUserLoading.value = false;
  }
};

// 组件挂载时加载用户
onMounted(() => {
  loadUsers();
});

// 获取错误类型
const getErrorType = (errorMessage: string): 'network' | 'server' | 'permission' | 'general' => {
  if (errorMessage.includes('网络') || errorMessage.includes('连接') || errorMessage.includes('超时')) {
    return 'network';
  }
  if (errorMessage.includes('服务器') || errorMessage.includes('500') || errorMessage.includes('502')) {
    return 'server';
  }
  if (errorMessage.includes('权限') || errorMessage.includes('授权') || errorMessage.includes('403')) {
    return 'permission';
  }
  return 'general';
};
</script>

<style lang="scss" scoped>
/* 额外的样式可以在这里添加 */
</style>
